#include "display_def.h"
#include <util.h>
#include <bulverde.h>

 //Note: PWMDCR0 max is 2^10

#define MIN_BRIGHT_VAL 0
#define MAX_BRIGHT_VAL  1023

void Gpio_SetAFR(int gpio_num, int function);


void BackLight_Open(DisplayContext *pCxt)
{
    GPDR0   = (GPDR0   | (0x1 << 16));
    GPSR0 |=0x00010000;

    //GAFR0_U = GAFR0_U & (~0x3);
    //GAFR0_U |= 0x2;
    Gpio_SetAFR(16, GPIO_AS_AF2);

    // enable PWM0
    PWMCR0 = 0;
    PWMDCR0 = 0x100;
    PWMPCR0 = 0x3FF;
    CKEN |= CKEN0_PWM0;
}

void BackLight_Close(DisplayContext *pCxt)
{
	////Set Pin16 Output & Low Level
	GPDR0	= (GPDR0   | (0x1 << 16));
	GPCR0	= (1 << 16);

	// disable PWM0
	CKEN &= ~CKEN0_PWM0;
}

int BackLight_SetBrightness(DisplayContext *pCxt, int  bright_val)
{
    // Check the arguments
    if ( bright_val < MIN_BRIGHT_VAL
        || bright_val >= MAX_BRIGHT_VAL) {
	    printk("\nError:  BackLight_SetBrightness() Parameters Illegal1\n");
	    return -1;
	}

    if (bright_val == 0) {
        BackLight_Close(pCxt);
    }
    else if (!(CKEN & CKEN0_PWM0)) {
        BackLight_Open(pCxt);
    }

    // look up the table
    PWMDCR0 = bright_val;
    return 0;
}
